const express = require('express')
const router = express.Router()
const {logI} = require('../log.js')
const {retError, retSuccess} = require('../utils/ret')
const userDb = require('../db/user-db')
const moment = require('moment')
const crypto = require('crypto')
const checkType = require('../utils/checkType')
const { v4: uuidv4} = require('uuid');

router
    .post('/', async(req, res) => {
        let {body: {name,maddr, pwd}} = req
        logI("A-S", maddr, "register", `${JSON.stringify(req.body)}`, "null")

        try {
            const error = checkType.register(req.body)
            if (error) {
                retError("register", maddr,10001,  error.details[0].message, res);
            } else {
                let data = {};
                data = await userDb.mailExist(maddr);
                if(!data || data.verify === 0){
                    const createTime = moment().format('YYYY-MM-DD HH:mm:ss');
                    const hashPass = crypto.createHmac('sha256', process.env.APP_SECRET)
                        .update(pwd)
                        .digest('hex')
                    const token =  uuidv4();
                    await userDb.register(maddr, hashPass, name,createTime,createTime,token,hashPass,name,createTime,createTime,token);
                    retSuccess("register", maddr,0, "", res);
                }else{
                    retError("register", maddr,10006, "user is exist", res);
                }
            }
        } catch (e) {
            retError("register", maddr,10001, e, res);
        }
    })

module.exports = router
